package org.csu.mypetstore.web.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;

public class NewOrderFormServlet extends HttpServlet {
    private static final String NEW_ORDER = "/WEB-INF/jsp/account/NewOrderForm.jsp";
    private static final String SIGNONFORM = "/WEB-INF/jsp/account/SignonForm.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    private Account account;
    private Order order;
    private Cart cart;

    public NewOrderFormServlet() {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        this.account = (Account)session.getAttribute("account");
        this.cart = (Cart)session.getAttribute("cart");
        if (this.account == null) {
            session.setAttribute("message", "You must sign on before attempting to check out.  Please sign on and try checking out again.");
            request.getRequestDispatcher(SIGNONFORM).forward(request, response);
        } else if (this.cart != null) {
            this.order = new Order();
            this.order.initOrder(this.account, this.cart);
            session.setAttribute("order", this.order);
            request.getRequestDispatcher(NEW_ORDER).forward(request, response);
        } else {
            session.setAttribute("message", "An order could not be created because a cart could not be found.");
            request.getRequestDispatcher(ERROR).forward(request, response);
        }

    }
}
